package com.artisan.spider.util;

import com.artisan.spider.config.SpiderConfig;
import com.artisan.spider.domain.SpError;
import com.artisan.spider.domain.SpLawChl;
import com.artisan.spider.service.ISpErrorService;
import com.artisan.spider.service.ISpLawChlService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.Locator;
import com.microsoft.playwright.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class SpiderUtil {

    @Autowired
    SpiderConfig spiderConfig;

    /**
     *
     * @param browser
     * @param mark
     * @param pageUrl
     * @param currentNum
     */
    public  void pageChuli(Browser browser,String mark,String pageUrl, int currentNum) {
        BrowserContext browserContext = browser.newContext();
        //每一页的地址
        Page page = browserContext.newPage();
        page.navigate(String.format(pageUrl, currentNum));
        Locator rows = page.locator("td a");

        int count = rows.count();

        for (int k = 0; k < count; k++) {
            // 判断是不是曾经抓取过
            QueryWrapper<SpLawChl> queryWrapper=new QueryWrapper();
            queryWrapper.eq("page_url",rows.nth(k).getAttribute("href"));
            int lawNumber=SpringContextUtil.getBean(ISpLawChlService.class).count(queryWrapper);
            if(lawNumber==0){
                BrowserContext bc = null;
                Page detail = null;
                try{
                    bc = browser.newContext();

                    detail= bc.newPage();
                    String href= spiderConfig.getDomain()+"/"+rows.nth(k).getAttribute("href");
                    detail.navigate(href);

                    log.info("第{}页-第{}篇文章的标题----->{},url为{},", currentNum, k + 1, rows.nth(k).textContent(),href);

                    String title=detail.locator(".qw-bt").textContent();


                    // 发布部门也可能存在多个
                    Locator fbbmLocator = detail.locator("td:right-of(:text(\"发布部门\"))");
                    String fbbm = "";
                    String fbbmCode = "";
                    if (fbbmLocator.count() != 0) {
                        Locator lb=fbbmLocator.nth(0).locator("a");
                        if (lb.count() != 0) {
                            if (lb.count() > 1) {
                                for (int i = 0; i < lb.count(); i++) {
                                    Locator locator=lb.nth(i);
                                    fbbmCode += getType(locator,"fdep_id","&menuname");
                                    fbbm +=locator.textContent();
                                    if(i!= lb.count()-1){
                                        fbbmCode+=",";
                                        fbbm+=",";
                                    }
                                }
                            } else {
                                Locator locator=lb.nth(0);
                                fbbm = locator.textContent();
                                fbbmCode=getType(locator,"fdep_id","&menuname");
                            }
                        }
                    }

                    String fwzh = "";
                    Locator fbzhLocator = detail.locator("td:right-of(:text(\"发文字号\"))");
                    if (fbzhLocator.count() != 0) {
                        fwzh = fbzhLocator.nth(0).textContent();
                    }

                    String fbrq = "";
                    Locator fbrqLocator = detail.locator("td:right-of(:text(\"发布日期\"))");
                    if (fbrqLocator.count() != 0) {
                        fbrq = fbrqLocator.nth(0).textContent();
                    }

                    String ssrq = "";
                    Locator ssrqLocator = detail.locator("td:right-of(:text(\"实施日期\"))");
                    if (ssrqLocator.count() != 0) {
                        ssrq = ssrqLocator.nth(0).textContent();
                    }


                    String ppbm = "";
                    String ppbmCode = "";
                    Locator ppbmLocator = detail.locator("td:right-of(:text(\"批准部门\"))");
                    if (ppbmLocator.count() != 0) {
                        Locator lb=ppbmLocator.nth(0).locator("a");
                        if (lb.count() != 0) {
                            if (lb.count() > 1) {
                                for (int i = 0; i < lb.count(); i++) {
                                    Locator locator=lb.nth(i);
                                    ppbmCode += getType(locator,"pdep_id","&menuname");
                                    ppbm +=locator.textContent();
                                    if(i!= lb.count()-1){
                                        ppbmCode+=",";
                                        ppbm+=",";
                                    }
                                }
                            } else {
                                Locator locator=lb.nth(0);
                                ppbm = locator.textContent();
                                ppbmCode=getType(locator,"pdep_id","&menuname");
                            }
                        }
                    }



                    String sxx = "";
                    String sxxCode="";
                    Locator sxxLocator = detail.locator("td:right-of(:text(\"时效性\"))");
                    if (sxxLocator.count() != 0) {
                        Locator locator=sxxLocator.nth(0).locator("a");
                        sxx = locator.textContent();
                        sxxCode=getType(locator,"shixiao_id","&menuname");
                    }

                    String xljb = "";
                    String xljbCode="";
                    Locator xljbLocator = detail.locator("td:right-of(:text(\"效力级别\"))");
                    if (xljbLocator.count() != 0) {
                        Locator locator=xljbLocator.nth(0).locator("a");
                        xljb = locator.textContent();
                        xljbCode=SpiderUtil.getType(locator,"xiaoli_id","&menuname");
                    }


                    // 法规类别有可能是多个
                    String fglb = "";
                    String fglbCode="";
                    Locator fglbLocator = detail.locator("td:right-of(:text(\"法规类别\"))");
                    if (fglbLocator.count() != 0) {
                        // 如果法规类别有多个
                        Locator lb = fglbLocator.nth(0).locator("a");
                        if (lb.count() != 0) {
                            if (lb.count() > 0) {
                                for (int i = 0; i < lb.count(); i++) {
                                    Locator locator=lb.nth(i);
                                    fglb += locator.textContent();
                                    fglbCode += getType(locator,"sort_id","&menuname");
                                    if(i!= lb.count()-1){
                                        fglb+=",";
                                        fglbCode+=",";
                                    }
                                }
                            } else {
                                Locator locator=lb.nth(0);
                                fglb = locator.textContent();
                                fglbCode=getType(locator,"sort_id","&menuname");
                            }
                        }
                    }
                    String content = detail.locator("#div_content").innerHTML();

                    log.info("发布部门名称,编码--》{},{}", fbbm,fbbmCode);
                    log.info("发文字号--》{}", fwzh);
                    log.info("发布日期--》{}", fbrq);
                    log.info("实施日期--》{}", ssrq);
                    log.info("时效性名称,编码--》{},{}", sxx,sxxCode);
                    log.info("效力级别名称,编码--》{},{}", xljb,xljbCode);
                    log.info("法规类别名称,编码--》{}", fglb,fglbCode);
                    log.info("*******************************第{}页-第{}篇文章处理完成", currentNum, k + 1);

                    SpLawChl spLawChl=new SpLawChl();
                    spLawChl.setId(UuidUtils.getUUid());
                    spLawChl.setFbDeptName(fbbm);
                    spLawChl.setFbDeptCode(fbbmCode);
                    spLawChl.setPzDeptName(ppbm);
                    spLawChl.setPzDeptCode(ppbmCode);
                    spLawChl.setLssuedNumber(fwzh);
                    spLawChl.setReleaseDate(fbrq);
                    spLawChl.setTimeName(sxx);
                    spLawChl.setTimeCode(sxxCode);
                    spLawChl.setXiaoliName(xljb);
                    spLawChl.setXiaoliCode(xljbCode);
                    spLawChl.setFaguiName(fglb);
                    spLawChl.setFaguiCode(fglbCode);
                    spLawChl.setImplDate(ssrq);
                    spLawChl.setTitle(title);
                    spLawChl.setFullText(content);
                    spLawChl.setStatus("1");
                    spLawChl.setCreateTime(DateUtil.getCurrentTime());
                    spLawChl.setPageUrl(rows.nth(k).getAttribute("href"));
                    spLawChl.setFgfl(mark);
                    spLawChl.setIsCreate("0");
                    SpringContextUtil.getBean(ISpLawChlService.class).save(spLawChl);

                    // 把数据发布到相应的消息对列中
                    SpringContextUtil.getBean(KafkaTemplate.class).send("messageQueen", spLawChl.getId());

                    detail.close();
                    bc.close();
                }catch (Exception e){
                    e.printStackTrace();
                    detail.close();
                    bc.close();
                    log.info("*******************************第{}页-第{}篇文章处理失败", currentNum, k + 1);
                    log.info("错误链接："+spiderConfig.getDomain()+"/"+rows.nth(k).getAttribute("href"));
                    SpError spError=new SpError();
                    spError.setCreateTime(DateUtil.getCurrentTime());
                    spError.setPageUrl(rows.nth(k).getAttribute("href"));
                    SpringContextUtil.getBean(ISpErrorService.class).save(spError);
                    continue;
                }
            }
            else{
                log.info("---------------此文章已处理过--------------");
                continue;
            }
        }
        page.close();
        browserContext.close();
    }

    /**
     *
     * @param locator
     * @param begin  开始标志
     * @param end    结束标志
     * @return
     */
    public static String getType(Locator locator,String begin,String end){
        //示例链接  ../index.aspx?Db=chl&EncodingName=gb2312&gj=1&sort_id=10003&menuname=law
        String href=locator.getAttribute("href");
        int sortId= href.indexOf(begin);
        int menuName=href.indexOf(end);
        String code=href.substring(sortId,menuName).split("=")[1];
        return  code;
    }
}




